package com.winer.interceptor;


import cn.hutool.core.util.StrUtil;
import com.winer.dto.UserDTO;
import com.winer.utils.JwtUtil;
import com.winer.utils.UserHolder;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;



import java.util.concurrent.TimeUnit;

import static com.winer.constant.JwtConstants.*;
import static com.winer.constant.RedisConstants.*;

public class RefreshTokenInterceptor implements HandlerInterceptor {


    private StringRedisTemplate stringRedisTemplate;

    public RefreshTokenInterceptor(StringRedisTemplate stringRedisTemplate){

        this.stringRedisTemplate = stringRedisTemplate;

    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {


        //获取请求头中的token

        String jwtToken = request.getHeader("Authorization");
        if (StrUtil.isEmptyIfStr(jwtToken)){

            return true;
        }

        String token = jwtToken.substring(6);
        //解析jwt令牌token
        Claims claims = JwtUtil.parseJWT(SECRET_KEY, token);
        Object userId = claims.get(TOKEN_PLAYLOAD);
        if(userId == null) {

            return true;
        }
        //从redis中获取user
        String key = USER_KEY + userId;
        Object phone = stringRedisTemplate.opsForHash().get(key, USER_PHONE_KEY);
        Object role = stringRedisTemplate.opsForHash().get(key, USER_ROLE_KEY);


        //判断用户是否存在
        if(phone == null) {

            return true;
        }

        //存在，保存到ThreadLocal
        UserDTO userDTO = new UserDTO();
        userDTO.setUserId(String.valueOf(userId));
        userDTO.setUserId(String.valueOf(phone));
        userDTO.setUserId(String.valueOf(role));
        UserHolder.saveUser(userDTO);

        //刷新有效期
        stringRedisTemplate.expire(key,TOKEN_TTL, TimeUnit.MILLISECONDS);

        //放行
        return true;
    }



    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

        UserHolder.removeUser();
    }
}
